<?php

//https://github.com/amphp/ext-fiber
// {"request_id":1,"type":"request","data":{"url":"/","method":"GET"}}

require_once './pm/CodeStream.php';

function pmWrite($request_id, $content, $type = 'response')
{
    $data = [
        'request_id' => $request_id,
        'type' => $type,
        'data' => $content,
    ];
    fwrite(STDOUT, json_encode($data) . "\n");
}

function pmRun($request_id, $data)
{
    if (is_array($data)) {
        list($method, $arguments) = $data;
        pmWrite($request_id, $arguments, $method);
    }
}

if (!preg_match("/cli/i", php_sapi_name())) {
    require "code://./php/index.php";
} else {
    require "code://./php/index.php";
    $requestMap = [];
    while ($input = fgets(STDIN)) {
        $input = json_decode($input, true);
        $request_id = $input['request_id'];
        $type = $input['type'];
        if ($type == 'request') {
            $fiber = new \Fiber(function () use ($request_id, &$requestMap) {
                ob_start();
                fiber_run();
                $response = ob_get_contents();
                ob_end_clean();
                pmWrite($request_id, $response);
                unset($requestMap[$request_id]);
            });
            $requestMap[$request_id] = $fiber;
            pmRun($request_id, $fiber->start());
        } else {
            if (isset($input['data'])) {
                pmRun($request_id, $requestMap[$request_id]->resume($input['data']));
            } else {
                pmRun($request_id, $requestMap[$request_id]->resume());
            }
        }
    }
}
